package controller;

import java.util.Date;
import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;

import model.Chatrecord;

public class indexController extends Controller {

	public void index() {

		render("/index.html");
	}

	public void getPublicCRList() {
	}
	
	public void getChatContent(){
		int roomnum = getParaToInt("roomNum");
		List<Chatrecord> list = Db.query("select * from (select * from chatrecord where 1=1 and roomnum = "+roomnum+" order by chatid desc limit 15) a order by a.chatid asc");

		renderJson(list);
		
	}
	
	public void submitChat(){
		Chatrecord newRecord = getModel(Chatrecord.class);
		newRecord.setChatdate(new Date());
		newRecord.save();
		renderJson("1");
	}
	
	public void getNewChatContent(){
		
		String lastId = getPara("lastId");
		int roomnum = getParaToInt("roomNum");
		int timeout = 5000;
		
		while(true&&timeout>0){
			List<Object> list = Db.query("select * from chatrecord where chatid > "+lastId+" and roomnum = "+roomnum+" order by chatid asc");
			if(list.size()>0){
				renderJson(list);
				break;
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			timeout -= 500;
		}
		if(timeout<=0)
			renderJson("");
	}

}
